package com.atguigu.base2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ticket{
    private int i=50;
    private final Lock lock =new ReentrantLock();
    public void sale(){
        lock.lock();
        try {
            if (i>0){System.out.println(Thread.currentThread().getName()+"买了第"+i--+"张票,还有"+i+"票");}

        }finally {
            lock.unlock();
        }
    }
}
public class Piao {
    public static void main(String[] args) {
        ticket t = new ticket();
        /*ticket t = new ticket();
        new Thread(()-> {for (int i = 0; i < 50; i++) t.sale();}, "A").start();
        new Thread(()-> {for (int i = 0; i < 50; i++) t.sale();}, "B").start();
        new Thread(()-> {for (int i = 0; i < 50; i++) t.sale();}, "C").start();*/
        /*ExecutorService threadPool = new ThreadPoolExecutor(
                1,
                1,
                1L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
            try {
                threadPool.execute(() -> {
                    for (int j = 0; j < 50; j++) {
                        t.sale();
                    }
                });
            }finally {
                threadPool.shutdown();
            }
*/
        ExecutorService pool = Executors.newFixedThreadPool(3);

        try {
            for (int i = 0; i < 50; i++) {
                pool.execute(()->{
                    t.sale();
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            pool.shutdown();
        }

    }

}
